package com.qf.sportsevent.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.qf.sportsevent.R;
import com.qf.sportsevent.adapter.CommonRecyclerAdapter;
import com.qf.sportsevent.databinding.FragmentNewsChildBinding;
import com.qf.sportsevent.entity.NewsBannersListHolderEntity;
import com.qf.sportsevent.entity.NewsContentsEntity;
import com.qf.sportsevent.entity.NewsDataEntity;
import com.qf.sportsevent.entity.NewsEntity;
import com.qf.sportsevent.util.FastEventBus;
import com.qf.sportsevent.util.HttpUtils;
import com.qf.sportsevent.util.RecyclerItemLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsChildFragment extends Fragment implements Callback {
    private String url;
    private FragmentNewsChildBinding binding;
    private CommonRecyclerAdapter<Object> recyclerAdapter;
    private int startId;

    public static NewsChildFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString("url",url);
        NewsChildFragment fragment = new NewsChildFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_news_child, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        url = getArguments().getString("url");
        recyclerAdapter = new CommonRecyclerAdapter<>(getContext(),new ArrayList<>(), RecyclerItemLayoutManager.getLayoutMap());
        binding.recycler.setAdapter(recyclerAdapter);
        binding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if(!recyclerView.canScrollVertically(1)){
                    StringBuilder stringBuilder = new StringBuilder(url);
                    stringBuilder.insert(stringBuilder.indexOf("&data_version"),"&start_id="+startId);
                    HttpUtils.okHttpAsyncGet(stringBuilder.toString(),NewsChildFragment.this);
                }
            }
        });
        HttpUtils.okHttpAsyncGet(url,this);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
            String jsonStr = response.body().string();
            NewsEntity newsEntity = JSON.parseObject(jsonStr, NewsEntity.class);
            NewsDataEntity newsDataEntity = newsEntity.getData();

            FastEventBus bus = new FastEventBus();
            bus.setNewsDataEntity(newsDataEntity);
            bus.setTag(url);
            EventBus.getDefault().post(bus);
    }

    @Override
    public void onFailure(Call call, IOException e) {}


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBusArrived(FastEventBus bus){
        if(bus.getMessage()!=null){
            Toast.makeText(getContext(),bus.getMessage(), Toast.LENGTH_SHORT).show();
        }

        if(bus.getTag() != null && !bus.getTag().equals(url)){
            return;
        }
        NewsDataEntity newsDataEntity = bus.getNewsDataEntity();
        if (newsDataEntity != null) {
            if (newsDataEntity.getBanners() != null && newsDataEntity.getBanners().size()>0) {
                recyclerAdapter.add(new NewsBannersListHolderEntity(newsDataEntity.getBanners()));
            }
            if (newsDataEntity.getContest_list() != null && newsDataEntity.getContest_list().size()>0) {
                recyclerAdapter.add(newsDataEntity.getContest_list());
            }
            List<NewsContentsEntity> tops = newsDataEntity.getTops();
            if (tops != null && tops.size()>0) {
                for (int i = 0; i < tops.size(); i++) {
                    tops.get(i).setTop(true);
                }
                recyclerAdapter.addAll(tops);
            }
            List<NewsContentsEntity> contents = newsDataEntity.getContents();
            if (contents != null && contents.size()>0) {
                startId = contents.get(contents.size()-1).getId();
                recyclerAdapter.addAll(contents);
            }
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

}
